package com.hkyp.ss.coursewebadmin.aop;

import com.hkyp.ss.course.apis.exception.UnacceptableException;
import com.hkyp.ss.coursewebadmin.dto.base.ResultBean;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 处理和包装异常
 */
@Aspect
@Component
public class ControllerAOP {
    private static final Logger logger = LoggerFactory.getLogger(ControllerAOP.class);

    @Pointcut("execution(public com.hkyp.ss.coursewebadmin.dto.base.ResultBean *(..))")
    public void controllerMethod(){}
    @Around("controllerMethod()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();

        ResultBean<?> result;

        //将从前端传来的参数打印日志
        Object[] arguments  = pjp.getArgs();
        //得到的是一个数组，将数组转为list打印
        logger.info("前端传来参数 "+ pjp.getSignature() +" =>>>"+Arrays.asList(arguments));




        try {
            result = (ResultBean<?>) pjp.proceed();
            logger.info(pjp.getSignature() + " 用时:" + (System.currentTimeMillis() - startTime));
        } catch (Throwable e) {
            result = handlerException(pjp, e);
        }

        return result;
    }

    private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
        ResultBean<?> result = new ResultBean();

        // 已知异常
        if (e instanceof UnknownAccountException) {  // 未知账户
            logger.error("UnknownAccountException");
            result.setMsg(e.getLocalizedMessage());
            result.setCode(ResultBean.UNKNOWN_ACCOUNT);
        }

        else if (e instanceof IncorrectCredentialsException) {  // 错误的凭证,密码不正确
            result.setMsg("账户或密码错误。"+e.getLocalizedMessage());
            result.setCode(ResultBean.INCORRECT_CREDENTIAL);
        }
        /**
         *  没有登录异常，或身份未认证
         */
        else if(e instanceof UnauthenticatedException){
            result.setMsg(e.getLocalizedMessage());
            result.setCode(ResultBean.NO_AUTHENTICATED);
        }
        else if(e instanceof UnauthorizedException){
            result.setMsg(e.getLocalizedMessage());  //可打印： 无此权限。
            result.setCode(ResultBean.NO_PERMISSION);
        }

        else if(e instanceof LockedAccountException){
            result.setMsg("账户被锁定，请联系管理员");
            result.setCode(ResultBean.LOCKED_ACCOUNT);
        }
        /**
         * 这个异常返回99状态码，告诉前端将msg里的信息渲染到页面展示给用户
         */
        else if(e instanceof UnacceptableException){
            // 将参数校验失败的信息返给前台展示
            result.setMsg(e.getLocalizedMessage());
            result.setCode(ResultBean.VALIDATE_ERROR);
        }

        /***************************************** 未知异常 *************************************************************/
        else {

            //TODO 未知的异常，应该格外注意，可以发送邮件通知等

            logger.error(pjp.getSignature() + " error ", e);
            logger.error("系统异常！！");
            //  System.out.println( e.getCause() );   e.getCause() 获取高级异常的底层异常
            result.setMsg("我们似乎遇到了些状况");
            result.setCode(ResultBean.FAIL);
        }

        return result;
    }
}


